<template>
  <!-- Modal Overlay -->
  <div v-if="dialogVisible" class="modal-overlay fixed inset-0 z-50 flex items-center justify-center p-4" @click="closeDialog">
    <div class="modal-content w-full max-w-7xl fade-in" @click.stop>
      <!-- Header -->
      <div class="gradient-bg text-white p-6 rounded-t-2xl">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <div class="w-12 h-12 bg-white/20 rounded-lg flex items-center justify-center">
              <i class="fas fa-chart-line text-2xl"></i>
            </div>
            <div>
              <h2 class="text-2xl font-bold">SEMRUSH 数据分析</h2>
              <p class="text-blue-100">{{ currentData?.domain || 'journalnewsinfo.com' }}</p>
              <p class="text-blue-100 text-sm mt-1">
                <i class="fas fa-clock mr-1"></i>
                数据更新时间: {{ getUpdateTime() }}
              </p>
            </div>
          </div>
          <div class="flex items-center space-x-4">
            <div class="glass-effect px-4 py-2 rounded-lg">
              <i class="fas fa-hashtag mr-2"></i>
              <span class="text-sm">Task ID: {{ currentData?.taskId || '5983363' }}</span>
            </div>
            <button 
              @click="closeDialog"
              class="w-10 h-10 bg-white/20 hover:bg-white/30 rounded-lg flex items-center justify-center transition-colors"
            >
              <i class="fas fa-times"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- Content -->
      <div class="p-6 space-y-6 max-h-[calc(95vh-120px)] overflow-y-auto">
        <!-- Tab Navigation -->
        <div class="flex space-x-2 bg-gray-50 p-2 rounded-lg">
          <button 
            :class="['trend-tab', { active: activeTab === 'domain' }]"
            @click="switchTab('domain')"
          >
            <i class="fas fa-globe mr-2"></i>
            外链域名（根域名）趋势
          </button>
          <button 
            :class="['trend-tab', { active: activeTab === 'links' }]"
            @click="switchTab('links')"
            :disabled="loadingBacklinks"
          >
            <i class="fas fa-link mr-2"></i>
            <span v-if="loadingBacklinks">
              <i class="fas fa-spinner fa-spin mr-2"></i>
              加载中...
            </span>
            <span v-else>外链精准链接趋势</span>
          </button>
        </div>

        <!-- Domain Trend Content -->
        <div v-show="activeTab === 'domain'" class="space-y-6">
          <!-- 流量数据概览 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div class="metric-card card-hover">
              <div class="flex items-center justify-between">
                <div>
                  <div class="text-sm text-gray-600 mb-1">自然搜索流量</div>
                  <div class="trend-value">{{ formatNumber(getMetricValue('totalLinks')) }}</div>
                  <!-- <div class="trend-indicator trend-up mt-2">
                    <i class="fas fa-arrow-up mr-1"></i>
                    +8%
                  </div> -->
                </div>
                <div class="w-16 h-16 relative">
                  <svg class="progress-ring w-16 h-16">
                    <circle class="progress-ring-circle" cx="32" cy="32" r="28"></circle>
                    <circle class="progress-ring-progress" cx="32" cy="32" r="28" style="stroke-dashoffset: 62.8;"></circle>
                  </svg>
                  <div class="absolute inset-0 flex items-center justify-center">
                    <i class="fas fa-link text-blue-600"></i>
                  </div>
                </div>
              </div>
            </div>


            <div class="metric-card card-hover">
              <div class="flex items-center justify-between">
                <div>
                  <div class="text-sm text-gray-600 mb-1">自然搜索关键词</div>
                  <div class="trend-value">{{ formatNumber(getMetricValue('totalKeywords')) }}</div>
                  <!-- <div class="trend-indicator trend-up mt-2">
                    <i class="fas fa-arrow-up mr-1"></i>
                    +8%
                  </div> -->
                </div>
                <div class="w-16 h-16 relative">
                  <svg class="progress-ring w-16 h-16">
                    <circle class="progress-ring-circle" cx="32" cy="32" r="28"></circle>
                    <circle class="progress-ring-progress" cx="32" cy="32" r="28" style="stroke-dashoffset: 62.8;"></circle>
                  </svg>
                  <div class="absolute inset-0 flex items-center justify-center">
                    <i class="fas fa-key text-blue-600"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 趋势图表 -->
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- 域名流量趋势 -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
              <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-800">域名流量趋势</h3>
                <div class="flex items-center space-x-2">
                  <span class="w-3 h-3 bg-blue-500 rounded-full"></span>
                  <span class="text-sm text-gray-600">总流量</span>
                  <span class="w-3 h-3 bg-green-500 rounded-full ml-4"></span>
                  <span class="text-sm text-gray-600">品牌流量</span>
                </div>
              </div>
              <div ref="trafficChartRef" class="chart-container"></div>
            </div>

            <!-- 域名关键词趋势 -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
              <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-800">域名关键词趋势</h3>
              </div>
              <div ref="keywordChartRef" class="chart-container"></div>
            </div>
          </div>
        </div>

        <!-- Links Trend Content -->
        <div v-show="activeTab === 'links'" class="space-y-6">
          <div v-if="loadingBacklinks" class="flex items-center justify-center py-20">
            <div class="text-center">
              <i class="fas fa-spinner fa-spin text-4xl text-blue-600 mb-4"></i>
              <p class="text-gray-600">正在加载外链精准数据...</p>
            </div>
          </div>
          
          <div v-else-if="backlinkError" class="text-center py-20">
            <div class="text-red-600">
              <i class="fas fa-exclamation-triangle text-4xl mb-4"></i>
              <p>{{ backlinkError }}</p>
              <button 
                @click="fetchBacklinkData" 
                class="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                重新加载
              </button>
            </div>
          </div>

          <div v-else-if="backlinkData" class="space-y-6">
            <!-- 外链精准数据概览 -->

            <!-- 外链精准趋势图表 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <!-- 外链流量趋势 -->
              <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="text-lg font-semibold text-gray-800">外链流量趋势</h3>
                  <div class="flex items-center space-x-2">
                    <span class="w-3 h-3 bg-blue-500 rounded-full"></span>
                    <span class="text-sm text-gray-600">总流量</span>
                    <span class="w-3 h-3 bg-green-500 rounded-full ml-4"></span>
                    <span class="text-sm text-gray-600">品牌流量</span>
                  </div>
                </div>
                <div ref="linkChartRef" class="chart-container"></div>
              </div>

              <!-- 外链关键词趋势 -->
              <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="text-lg font-semibold text-gray-800">外链关键词趋势</h3>
                </div>
                <div ref="qualityChartRef" class="chart-container"></div>
              </div>
            </div>

            <!-- 外链详细信息 -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
              <h3 class="text-lg font-semibold text-gray-800 mb-4">外链详细信息</h3>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <div class="space-y-3">
                    <div class="flex">
                       <span class="text-gray-600">锚文本:</span>
                       <span class="font-medium ml-5">{{ backlinkData?.anchor_text }}</span>
                     </div>
                     <div class="flex">
                       <span class="text-gray-600">原始URL:</span>
                       <a :href="backlinkData?.original_url" target="_blank" class="ml-5 text-blue-600 hover:text-blue-800 truncate ">
                         {{ backlinkData?.original_url }}
                       </a>
                     </div>
                     <div class="flex">
                       <span class="text-gray-600">目标URL:</span>
                       <a :href="backlinkData?.resolved_url" target="_blank" class="ml-5 text-blue-600 hover:text-blue-800 truncate">
                         {{ backlinkData?.resolved_url }}
                       </a>
                     </div>
                   </div>
                 </div>
                 <div>
                   <div class="space-y-3">
                     <div class="flex justify-between">
                       <span class="text-gray-600">域名匹配:</span>
                       <span :class="backlinkData?.domain_match === 'error' ? 'text-red-600' : 'text-green-600'">
                         {{ backlinkData?.domain_match }}
                       </span>
                     </div>
                     <div class="flex justify-between">
                       <span class="text-gray-600">Google索引:</span>
                       <span :class="backlinkData?.google_indexed?.is_indexed ? 'text-green-600' : 'text-red-600'">
                         {{ backlinkData?.google_indexed?.is_indexed ? '已索引' : '未索引' }}
                       </span>
                     </div>
                     <div class="flex justify-between">
                       <span class="text-gray-600">状态码:</span>
                       <span :class="backlinkData?.google_indexed?.status_code === 200 ? 'text-green-600' : 'text-red-600'">
                         {{ backlinkData?.google_indexed?.status_code }}
                       </span>
                     </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Top Keywords 排行 -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          <div class="p-6 border-b border-gray-200">
            <div class="flex items-center justify-between">
              <h3 class="text-xl font-semibold text-gray-800">外链Top Keywords 排行</h3>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-500">显示前</span>
                <select class="border border-gray-300 rounded px-2 py-1 text-sm">
                  <option>10</option>
                </select>
                <span class="text-sm text-gray-500">条</span>
              </div>
            </div>
          </div>
          
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-gray-50">
                <tr>
                  <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">排名</th>
                  <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">关键词</th>
                  <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">流量</th>
                  <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">搜索量</th>
                  <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">CPC占比</th>
                  <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">流量占比</th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr 
                  v-for="(keyword, index) in getKeywordData().slice(0, 10)" 
                  :key="index"
                  class="hover:bg-gray-50 transition-colors"
                                  >
                    <td class="px-6 py-4 whitespace-nowrap">
                    <span :class="['ranking-badge', index === 0 ? 'rank-1' : index === 1 ? 'rank-2' : index === 2 ? 'rank-3' : 'rank-other']">{{ index + 1 }}</span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm font-medium text-gray-900">{{ keyword.phrase || 'N/A' }}</div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-gray-900">{{ new Intl.NumberFormat('en-US').format(keyword.traffic || 0) }}</div>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                      {{ (keyword.trends && keyword.trends.length > 0) ? ((keyword.trends[keyword.trends.length - 1] >= 10000) ? `${(keyword.trends[keyword.trends.length - 1] / 10000).toFixed(2)}K` : keyword.trends[keyword.trends.length - 1].toString()) : '0' }}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                      {{ keyword.cpc || 0 }}%
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                      {{ keyword.trafficPercent || 0 }}%
                    </span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, nextTick, computed, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';
import { BASE_URL } from '../main';

interface TrendDataItem {
  date: string;
  traffic: number;
  trafficBranded: number;
  trafficNonBranded: number;
  trafficCost: number;
  organicPositionsTrend: number[];
  serpFeaturesPositions: number;
}

interface BacklinkDataItem {
  adwordsPositions: number;
  adwordsPositionsTrend: number[];
  adwordsTraffic: number;
  adwordsTrafficCost: number;
  date: string;
  organicPositions: number;
  organicPositionsBranded: number;
  organicPositionsTrend: number[];
  organicTraffic: number;
  organicTrafficBranded: number;
  organicTrafficCost: number;
  organicTrafficNonBranded: number;
  positions: number;
  positionsBranded: number;
  rank: number;
  serpFeaturesPositions: number;
  serpFeaturesPositionsBranded: number;
  serpFeaturesTraffic: number;
  serpFeaturesTrafficBranded: number;
  serpFeaturesTrafficCost: number;
  serpFeaturesTrafficNonBranded: number;
  traffic: number;
  trafficBranded: number;
  trafficCost: number;
  trafficNonBranded: number;
}

interface BacklinkResponse {
  anchor_text: string;
  original_url: string;
  resolved_url: string;
  domain_match: string;
  last_checked?: string;
  backlink_traffic?: number;
  check_data?: {
    word_count: number;
  };
  google_indexed: {
    is_indexed: boolean;
    check_time: string;
    status_code: number;
    message: string;
    details: {
      unfriendly_reasons: string[];
      friendly_signals: string[];
    };
  };
  semrush_data: {
    overview_trend: TrendDataItem[];
    keyword_ranking: any[];
  };
}

interface SemrushData {
  taskId?: string;
  domain?: string;
  updated_at?: string;
  traffic_data?: {
    organic: number;
    paid: number;
  };
  overview_trend?: {
    data: TrendDataItem[];
  };
  keyword_ranking?: {
    data: any[];
  };
  top_keywords?: any[];
}

const props = defineProps<{
  visible: boolean;
  data: SemrushData;
  siteId?: number;
}>();

const emit = defineEmits(['update:visible']);

const dialogVisible = ref(props.visible);
const trafficChartRef = ref<HTMLElement | null>(null);
const keywordChartRef = ref<HTMLElement | null>(null);
const linkChartRef = ref<HTMLElement | null>(null);
const qualityChartRef = ref<HTMLElement | null>(null);
const currentData = ref(props.data);
const activeTab = ref('domain');
const backlinkData = ref<BacklinkResponse | null>(null);
const loadingBacklinks = ref(false);
const backlinkError = ref('');

let trafficChart: echarts.ECharts | null = null;
let keywordChart: echarts.ECharts | null = null;
let linkChart: echarts.ECharts | null = null;
let qualityChart: echarts.ECharts | null = null;

watch(() => props.visible, (val) => {
  dialogVisible.value = val;
  if (val) {
    nextTick(() => {
      initCharts();
    });
  }
});

watch(() => props.data, (val) => {
  currentData.value = val;
  if (val && dialogVisible.value) {
    nextTick(() => {
      initCharts();
    });
  }
});

const formatNumber = (num: number) => {
  return new Intl.NumberFormat('en-US').format(num);
};

const formatSearchVolume = (volume: number) => {
  if (volume >= 10000) {
    return `${(volume / 10000).toFixed(2)}K`;
  }
  return volume.toString();
};

const getUpdateTime = () => {
  let updateTime: string | undefined;
  
  if (activeTab.value === 'domain') {
    updateTime = currentData.value?.updated_at;
  } else if (activeTab.value === 'links') {
    updateTime = backlinkData.value?.last_checked;
  }
  
  if (!updateTime) {
    return '暂无数据';
  }
  
  try {
    const date = new Date(updateTime);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    });
  } catch (e) {
    return updateTime;
  }
};

const closeDialog = () => {
  emit('update:visible', false);
  console.log("backlinkData",backlinkData.value);
  // 清空backlinkData
  backlinkData.value = null;
  loadingBacklinks.value = false;
  activeTab.value = 'domain';
};

const fetchBacklinkData = async () => {
  if (!props.siteId) {
    backlinkError.value = '缺少站点ID';
    return;
  }

  loadingBacklinks.value = true;
  backlinkError.value = '';
  

  try {
    const response = await fetch(`${BASE_URL}/api/v1/backlinks/${props.siteId}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    backlinkData.value = data;
    console.log("完整的外链数据结构:", backlinkData.value);
    console.log("数据的键:", Object.keys(backlinkData.value || {}));
    
    // 数据加载完成后重新初始化图表
    await nextTick();
    initCharts();
  } catch (error) {
    console.error('获取外链数据失败:', error);
    backlinkError.value = '获取外链数据失败，请稍后重试';
  } finally {
    loadingBacklinks.value = false;
  }
};

const switchTab = async (tab: string) => {
  activeTab.value = tab;
  console.log("tab",tab ,backlinkData.value,loadingBacklinks.value);

  if (tab === 'links' && !backlinkData.value && !loadingBacklinks.value) {
    await fetchBacklinkData();
  }
  
  nextTick(() => {
    initCharts();
  });
};

const getLatestTraffic = () => {
  const data = currentData.value?.overview_trend?.data;
  if (!data || data.length === 0) return 0;
  return data[data.length - 1]?.traffic || 0;
};

const getBrandedTraffic = () => {
  const data = currentData.value?.overview_trend?.data;
  if (!data || data.length === 0) return 0;
  return data[0]?.trafficBranded || 0;
};

const getTrafficCost = () => {
  const data = currentData.value?.overview_trend?.data;
  if (!data || data.length === 0) return 0;
  return data[0]?.trafficCost || 0;
};

// 外链数据相关的计算函数
const getBacklinkLatestTraffic = () => {
  const data = backlinkData.value?.semrush_data?.overview_trend;
  if (!data || data.length === 0) return 0;
  return data[data.length - 1]?.traffic || 0;
};

const getBacklinkAdwordsTraffic = () => {
  const data = backlinkData.value?.semrush_data?.overview_trend;
  if (!data || data.length === 0) return 0;
  return data[data.length - 1]?.trafficNonBranded || 0;
};

const getBacklinkBrandedTraffic = () => {
  const data = backlinkData.value?.semrush_data?.overview_trend;
  if (!data || data.length === 0) return 0;
  return data[data.length - 1]?.trafficBranded || 0;
};

const getBacklinkTrafficCost = () => {
  const data = backlinkData.value?.semrush_data?.overview_trend;
  if (!data || data.length === 0) return 0;
  return data[data.length - 1]?.trafficCost || 0;
};

const getMetricValue = (metric: string) => {
  if (metric === 'totalLinks') {
    const data = currentData.value?.overview_trend?.data;
    if (!data || data.length === 0) return 0;
    return data[data.length - 1]?.traffic || 0;
  } else if (metric === 'totalKeywords') {
    const data = currentData.value?.overview_trend?.data;
    if (!data || data.length === 0) return 0;
    
    let lastest_keyword_count = 0;
    const lastest_keyword_trend = data[data.length - 1]?.organicPositionsTrend;
    if (lastest_keyword_trend) {
      for (let i = 0; i < lastest_keyword_trend.length; i++) {
        lastest_keyword_count += lastest_keyword_trend[i] || 0;
      }
    }

    return lastest_keyword_count;
  }
  return 0;
};

const getRankingClass = (rank: number) => {
  if (rank === 1) return 'rank-1';
  if (rank === 2) return 'rank-2';
  if (rank === 3) return 'rank-3';
  return 'rank-other';
};

const keywordRankings = computed(() => {
  return (currentData.value?.keyword_ranking?.data || []).slice(0, 10);
});

const getKeywordData = () => {
  console.log("getKeywordData: activeTab=", activeTab.value);
  console.log("getKeywordData: backlinkData存在=", !!backlinkData.value);
  console.log("getKeywordData: backlinkData.semrush_data=", backlinkData.value?.semrush_data);
  console.log("getKeywordData: backlinkData.semrush_data.keyword_ranking=", backlinkData.value?.semrush_data?.keyword_ranking);

  // 检查外链数据是否存在且关键词数组不为空
  if (activeTab.value === 'links') {
    console.log("使用外链数据:", backlinkData.value?.semrush_data?.keyword_ranking);
    return backlinkData.value?.semrush_data?.keyword_ranking || [];
  }
  
  console.log("使用域名数据:", currentData.value?.keyword_ranking?.data || []);
  return currentData.value?.keyword_ranking?.data || [];
};

const initCharts = async () => {
  await nextTick();
  console.log("initCharts: activeTab=", activeTab.value);
  console.log("initCharts: currentData存在=", !!currentData.value?.overview_trend?.data);
  console.log("initCharts: backlinkData存在=", !!backlinkData.value?.semrush_data?.overview_trend);

  // 销毁旧的图表实例
  trafficChart?.dispose();
  keywordChart?.dispose();
  linkChart?.dispose();
  qualityChart?.dispose();

  if (activeTab.value === 'domain' && currentData.value?.overview_trend?.data) {
    const trendData = currentData.value.overview_trend.data;
    const dates = trendData.map((item: TrendDataItem) => {
      const dateStr = item.date;
      return `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}`;
    });

    // 初始化域名流量趋势图
    if (trafficChartRef.value) {
      trafficChart = echarts.init(trafficChartRef.value);
      const trafficOption: EChartsOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['总流量', '品牌流量'],
          top: 'top',
          selected: {
            '总流量': true,
            '品牌流量': true
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value',
          name: '流量'
        },
        series: [
          {
            name: '总流量',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => item.traffic),
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#3b82f6'
            },
            areaStyle: {
              color: 'rgba(59, 130, 246, 0.1)'
            }
          },
          {
            name: '品牌流量',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => item.trafficBranded),
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#10b981'
            },
            areaStyle: {
              color: 'rgba(16, 185, 129, 0.1)'
            }
          }
        ]
      };
      trafficChart.setOption(trafficOption);
    }

    // 初始化域名关键词趋势图
    if (keywordChartRef.value) {
      keywordChart = echarts.init(keywordChartRef.value);
      const keywordOption: EChartsOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['排名前3', '排名4-10', '排名11-20', '排名21-50', '排名51-100', 'SERP精选'],
          top: 'top',
          selected: {
            '排名前3': true,
            '排名4-10': true,
            '排名11-20': true,
            '排名21-50': true,
            '排名51-100': true,
            'SERP精选': true
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value',
          name: '关键词数量'
        },
        series: [
          {
            name: '排名前3',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => item.organicPositionsTrend[0]),
            smooth: true,
            color: '#ef4444',
            lineStyle: {
              width: 3,
              color: '#ef4444'
            }
          },
          {
            name: '排名4-10',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => item.organicPositionsTrend[1]),
            smooth: true,
            color: '#f59e0b',
            lineStyle: {
              width: 3,
              color: '#f59e0b'
            }
          },
          {
            name: '排名11-20',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => item.organicPositionsTrend[2]),
            smooth: true,
            color: '#3b82f6',
            lineStyle: {
              width: 3,
              color: '#3b82f6'
            }
          },
          {
            name: '排名21-50',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => {
              const trend = item.organicPositionsTrend;
              return (trend[3] || 0) + (trend[4] || 0) + (trend[5] || 0);
            }),
            smooth: true,
            color: '#06b6d4',
            lineStyle: {
              width: 3,
              color: '#06b6d4'
            }
          },
          {
            name: '排名51-100',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => {
              const trend = item.organicPositionsTrend;
              let sum = 0;
              for (let i = 6; i <= 10 && i < trend.length; i++) {
                sum += trend[i] || 0;
              }
              return sum;
            }),
            smooth: true,
            color: '#93c5fd',
            lineStyle: {
              width: 3,
              color: '#93c5fd'
            }
          },
          {
            name: 'SERP精选',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => item.serpFeaturesPositions),
            smooth: true,
            color: '#8b5cf6',
            lineStyle: {
              width: 3,
              color: '#8b5cf6'
            }
          }
        ]
      };
      keywordChart.setOption(keywordOption);
    }
  } else if (activeTab.value === 'links' && backlinkData.value?.semrush_data?.overview_trend) {
    const trendData = backlinkData.value.semrush_data.overview_trend;
          const dates = trendData.map((item: TrendDataItem) => {
      const dateStr = item.date;
      return `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}`;
    });

    // 初始化外链流量趋势图
    if (linkChartRef.value) {
      linkChart = echarts.init(linkChartRef.value);
      const linkOption: EChartsOption = {
        title: {
          text: `历史流量总和：${getBacklinkCalData("traffic")}`,
          left: 'center',
          textStyle: {
            fontSize: 15,
            color: '#666'
          },
          top: 0
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['总流量', '品牌流量'],
          top: '30px',
          selected: {
            '总流量': true,
            '品牌流量': true
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value',
          name: '流量'
        },
                  series: [
            {
              name: '总流量',
              type: 'line',
              data: trendData.map((item: TrendDataItem) => item.traffic),
              smooth: true,
              lineStyle: {
                width: 3,
                color: '#3b82f6'
              },
              areaStyle: {
                color: 'rgba(59, 130, 246, 0.1)'
              }
            },
            {
              name: '品牌流量',
              type: 'line',
              data: trendData.map((item: TrendDataItem) => item.trafficBranded),
              smooth: true,
              lineStyle: {
                width: 3,
                color: '#10b981'
              },
              areaStyle: {
                color: 'rgba(16, 185, 129, 0.1)'
              }
            }
          ]
      };
      linkChart.setOption(linkOption);
    }

    // 初始化外链关键词趋势图
    if (qualityChartRef.value) {
      qualityChart = echarts.init(qualityChartRef.value);
      const qualityOption: EChartsOption = {
        title: {
          text: `历史关键词总和：${getBacklinkCalData("keywords")}`,
          left: 'center',
          textStyle: {
            fontSize: 15,
            color: '#666'
          },
          top: 0
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['排名前3', '排名4-10', '排名11-20', '排名21-50', '排名51-100', 'SERP精选'],
          top: '30px',
          selected: {
            '排名前3': true,
            '排名4-10': true,
            '排名11-20': true,
            '排名21-50': true,
            '排名51-100': true,
            'SERP精选': true
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '25%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value',
          name: '关键词数量'
        },
        series: [
          {
            name: '排名前3',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => item.organicPositionsTrend[0]),
            smooth: true,
            color: '#ef4444',
            lineStyle: {
              width: 3,
              color: '#ef4444'
            }
          },
          {
            name: '排名4-10',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => item.organicPositionsTrend[1]),
            smooth: true,
            color: '#f59e0b',
            lineStyle: {
              width: 3,
              color: '#f59e0b'
            }
          },
          {
            name: '排名11-20',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => item.organicPositionsTrend[2]),
            smooth: true,
            color: '#3b82f6',
            lineStyle: {
              width: 3,
              color: '#3b82f6'
            }
          },
          {
            name: '排名21-50',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => {
              const trend = item.organicPositionsTrend;
              return (trend[3] || 0) + (trend[4] || 0) + (trend[5] || 0);
            }),
            smooth: true,
            color: '#06b6d4',
            lineStyle: {
              width: 3,
              color: '#06b6d4'
            }
          },
          {
            name: '排名51-100',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => {
              const trend = item.organicPositionsTrend;
              let sum = 0;
              for (let i = 6; i <= 10 && i < trend.length; i++) {
                sum += trend[i] || 0;
              }
              return sum;
            }),
            smooth: true,
            color: '#93c5fd',
            lineStyle: {
              width: 3,
              color: '#93c5fd'
            }
          },
          {
            name: 'SERP精选',
            type: 'line',
            data: trendData.map((item: TrendDataItem) => item.serpFeaturesPositions),
            smooth: true,
            color: '#8b5cf6',
            lineStyle: {
              width: 3,
              color: '#8b5cf6'
            }
          }
        ]
      };
      qualityChart.setOption(qualityOption);
    }
  }

  // 监听窗口大小变化
  const handleResize = () => {
    trafficChart?.resize();
    keywordChart?.resize();
    linkChart?.resize();
    qualityChart?.resize();
  };

  window.addEventListener('resize', handleResize);

  // 在组件销毁时移除事件监听
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
    trafficChart?.dispose();
    keywordChart?.dispose();
    linkChart?.dispose();
    qualityChart?.dispose();
  });
};

const getBacklinkCalData = (type: string) => {
  if (type === "traffic") {
    return backlinkData.value?.backlink_traffic || 0;
  } else if (type === "keywords") {
    return backlinkData.value?.check_data?.word_count || 0;
  }
  return 0;
};

onMounted(() => {
  if (currentData.value && dialogVisible.value) {
    initCharts();
  }
});
</script>

<style scoped>
.modal-overlay {
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
}

.modal-content {
  background: white;
  border-radius: 16px;
  max-width: 95vw;
  max-height: 95vh;
  overflow-y: auto;
}

.glass-effect {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.gradient-bg {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-hover {
  transition: all 0.3s ease;
}

.card-hover:hover {
  transform: translateY(-2px);
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.metric-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
}

.metric-card:hover {
  border-color: #3b82f6;
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.1);
}

.trend-tab {
  padding: 12px 24px;
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;
  font-weight: 500;
}

.trend-tab.active {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.trend-tab:not(.active) {
  background: #f8fafc;
  color: #64748b;
}

.trend-tab:not(.active):hover {
  background: #e2e8f0;
  color: #374151;
}

.chart-container {
  position: relative;
  height: 320px;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.ranking-badge {
  display: inline-block;
  width: 28px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  border-radius: 50%;
  font-weight: bold;
  font-size: 14px;
}

.rank-1 { background: #ef4444; color: white; }
.rank-2 { background: #f59e0b; color: white; }
.rank-3 { background: #3b82f6; color: white; }
.rank-other { background: #e5e7eb; color: #6b7280; }

.progress-ring {
  transform: rotate(-90deg);
}

.progress-ring-circle {
  stroke: #e5e7eb;
  stroke-width: 4;
  fill: transparent;
  stroke-linecap: round;
}

.progress-ring-progress {
  stroke: #3b82f6;
  stroke-width: 4;
  fill: transparent;
  stroke-linecap: round;
  stroke-dasharray: 251.2;
  stroke-dashoffset: 125.6;
  transition: stroke-dashoffset 1s ease;
}

.fade-in {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.trend-value {
  font-size: 2.5rem;
  font-weight: 700;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.trend-indicator {
  display: inline-flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.trend-up {
  background: #dcfce7;
  color: #166534;
}

.trend-down {
  background: #fee2e2;
  color: #991b1b;
}
</style> 